package client;

import java.io.IOException;

import ocsf.client.ObservableClient;
import entities.Message;

/**
 * Manage all data transfers between client and server
 */
public class ClientHandler extends ObservableClient{
	private ClientIF clientUI;
	
	public ClientHandler(String host, int port, ClientIF clientUI) throws IOException {
		super(host, port); 		//Call the superclass constructor
		this.clientUI = clientUI;
		openConnection();
	}

	@Override
	protected void handleMessageFromServer(Object msg) {
		clientUI.readMsg((Message)msg);
	}
	
	/**
	 * get a message from UI and sends it to server
	 * @param message to be sent
	 * @throws ServerComException server communication error
	 */
	public void handleMessageFromClientUI(Message message) {
		try {
			sendToServer(message);
		} catch (IOException e) {
			System.err.println("Could not send message to server. Terminating client. Error: " + e.getMessage());
		}
	}
		
	/**
	 * closes the connection to server
	 */
	public void quit() {
		try{
	      closeConnection();
	    }
	    catch(IOException e) {}
	    System.exit(0);
	}
}